package com.ilarele.shopping.client.activities;

import java.util.ArrayList;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SeekBar;

import com.flurry.android.FlurryAgent;
import com.ilarele.shopping.Message;
import com.ilarele.shopping.Product;
import com.ilarele.shopping.ProductLocation;
import com.ilarele.shopping.client.R;
import com.ilarele.shopping.client.adaptors.A2SimpleProductAdapter;
import com.ilarele.shopping.client.util.Communication;
import com.ilarele.shopping.client.util.DBUtil;
import com.ilarele.shopping.client.util.DrawableManager;
import com.ilarele.shopping.client.util.Global;

public class A2MyInfoActivity extends Activity {

	protected static final int DIALOG_EDIT_PROD = 0;

	protected static final int RESULT_MAP_VIEW = 1;
	protected static final int RESULT_TAKE_PICTURE = 2;

	private ListView mListItems;
	private A2SimpleProductAdapter mAdapter;
	protected Product mDialogProd;
	private Button toUpdatePlace;
	private ProductLocation updateLocation;

	private String updatePicPath;

	private ImageView initProductPicture;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.a2_my_tab);

		ArrayList<Product> prods = DBUtil.getMyProducts(this);
		mListItems = (ListView) findViewById(R.id.my_items_list);
		final Button moreBtn = new Button(this);
		moreBtn.setTextAppearance(A2MyInfoActivity.this,
				R.style.pink_button_style);
		moreBtn.setBackgroundResource(R.drawable.blue_button);
		moreBtn.setText(R.string.refresh);
		mListItems.addHeaderView(moreBtn);

		mAdapter = new A2SimpleProductAdapter(this, prods);
		mListItems.setAdapter(mAdapter);
		mListItems.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				mDialogProd = mAdapter.getItem(position - 1);
				showDialog(DIALOG_EDIT_PROD);
			}
		});

		moreBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						mAdapter.clear();
						mAdapter.notifyDataSetChanged();
					}
				});
				final ArrayList<Product> prods = DBUtil
						.getMyProducts(A2MyInfoActivity.this);
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						for (Product prod : prods) {
							mAdapter.add(prod);
							mAdapter.notifyDataSetChanged();
						}
					}
				});
			}
		});
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_EDIT_PROD:
			final Dialog dialog = new Dialog(this);
			final Product localProd = mDialogProd;
			dialog.setContentView(R.layout.dialog_my_item);
			dialog.setTitle("Init Product");

			initProductPicture = (ImageView) dialog
					.findViewById(R.id.dlg_picture);
			initProductPicture.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					Intent intent = new Intent(A2MyInfoActivity.this,
							TakePictureActivity.class);
					startActivityForResult(intent, RESULT_TAKE_PICTURE);
				}
			});

			final EditText name = (EditText) dialog.findViewById(R.id.dlg_name);
			name.setText(localProd.pName.name);
			final EditText price = (EditText) dialog
					.findViewById(R.id.dlg_price);
			price.setText(localProd.pInfo.price + "");
			final EditText tags = (EditText) dialog.findViewById(R.id.dlg_tags);
			tags.setText(localProd.pTags.tags);
			final SeekBar rating = (SeekBar) dialog
					.findViewById(R.id.dlg_rating);
			rating.setProgress(localProd.pInfo.rating);
			toUpdatePlace = (Button) dialog.findViewById(R.id.dlg_change_place);
			toUpdatePlace.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					Intent intent = new Intent(A2MyInfoActivity.this,
							CustomEditMapView.class);
					startActivityForResult(intent, RESULT_MAP_VIEW);
				}
			});

			final Button submit = (Button) dialog.findViewById(R.id.dlg_submit);
			submit.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View arg0) {
					final Message msg = new Message();
					msg.type = Message.TYPE_CLIENT_INIT_PROD;
					msg.idClient = Global.clientId;
					localProd.pName.name = name.getText().toString();
					localProd.pTags.tags = tags.getText().toString();
					localProd.pInfo.price = Float.parseFloat(price.getText()
							.toString());
					localProd.pInfo.rating = rating.getProgress();
					if (updateLocation != null)
						localProd.pInfo.pLocation = updateLocation;
					msg.content = localProd;

					new Thread(new Runnable() {
						@Override
						public void run() {
							localProd.pPicture.imageUrl = updatePicPath;
							Communication.sendMessage(msg, false);
						}
					}).start();
					new Thread(new Runnable() {
						@Override
						public void run() {
							Communication.uploadPicture(updatePicPath);
						}
					}).start();

					// add to DB
					DBUtil.updateProduct(A2MyInfoActivity.this, localProd);
					runOnUiThread(new Runnable() {
						public void run() {
							mAdapter.notifyDataSetInvalidated();
						}
					});
					dialog.cancel();
				}
			});

			final Button changePlace = (Button) dialog
					.findViewById(R.id.dlg_change_place);
			changePlace.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View arg0) {
					// open a MapView
					Intent intent = new Intent(arg0.getContext(),
							CustomEditMapView.class);
					startActivityForResult(intent, RESULT_MAP_VIEW);
				}
			});
			return dialog;
		default:
			break;
		}
		return super.onCreateDialog(id);
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (Global.dbWasCleared()) {
			mAdapter.clear();
			mAdapter.notifyDataSetChanged();
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		System.out.println("resultCode " + resultCode + "   requestCode "
				+ requestCode);
		if (resultCode == RESULT_OK) {
			if (requestCode == RESULT_MAP_VIEW) {
				String location = intent.getStringExtra("location");
				if (location != null) {
					// TODO: use those
					double latitude = intent.getDoubleExtra("latitude", 0);
					double longitude = intent.getDoubleExtra("longitude", 0);

					updateLocation = new ProductLocation(location, latitude,
							longitude);
					toUpdatePlace.setText(location);
				}
			} else if (requestCode == RESULT_TAKE_PICTURE) {
				System.out
						.println("path from takepicactivity " + updatePicPath);
				updatePicPath = intent.getStringExtra("imagePath");
				DrawableManager.fetchLocalView(updatePicPath,
						initProductPicture);
			}
		} else if (resultCode == RESULT_CANCELED) {
			// Handle cancel
		}
	}

	@Override
	public void onStart() {
		super.onStart();
		if (!Global.DEBUG_MODE)
			FlurryAgent.onStartSession(this, Global.FLURRY_ID);
	}

	@Override
	public void onStop() {
		super.onStop();
		if (!Global.DEBUG_MODE)
			FlurryAgent.onEndSession(this);
	}
}
